package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.*;
import com.tanhua.model.domain.mongo.Comment;
import com.tanhua.model.domain.mysql.UserInfo;
import com.tanhua.model.domain.vo.CommentVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.exception.ErrorResult;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author lk
 * @date 2022-03-28
 */
@Slf4j
@Service
public class CommentService {
    @DubboReference
    private CommentApi commentApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private MovementApi movementApi;
    @Autowired
    private RedisTemplate redisTemplate;

    //分页查询评论列表
    public PageResult findComments(Integer page, Integer pagesize, String movementId) {
        //调用API查询评论列表
        List<Comment> list = commentApi.findComments(movementId,page,pagesize,CommentType.COMMENT);
        //判断list集合是否存在
        if (CollUtil.isEmpty(list)){
            return new PageResult();
        }
        //提取所有的用户id,调用UserInfoAPI查询用户详情
        List<Long> userIds= CollUtil.getFieldValues(list, "userId", Long.class);
        //获取评论的所有用户详细信息
        Map<Long, UserInfo> infoMap = userInfoApi.findByIds(userIds, null);
        //构造vo集合来装返回数据
        List<CommentVo> vos = new ArrayList<>();
        //循环列表
        for (Comment comment : list) {
            //获取对应的用户信息
            UserInfo userInfo = infoMap.get(comment.getUserId());
            if(userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo,comment);
                vos.add(vo);
            }
        }
        return new PageResult(page,pagesize,0,vos);
    }

    //发布评论
    public void saveComments(String movementId, String comment) {
        //获取操作用户id
        Long userId = UserHolder.getUserId();
        //构造Comment
        Comment com = new Comment();
        com.setCommentType(CommentType.COMMENT.getType());
        com.setCreated(System.currentTimeMillis());
        com.setPublishId(new ObjectId(movementId));
        com.setUserId(userId);
        com.setContent(comment);
        //调用API保存评论
        Integer commentCount = commentApi.save(com);
        log.info("commentCount = " + commentCount);
    }

    //点赞
    public Integer likeComment(String movementId) {
        //调用API查询用户是否已点赞
        Boolean hasComment = commentApi.hasComment(movementId, UserHolder.getUserId(), CommentType.LIKE);
        //如果已经点赞，抛出异常
        if (hasComment){
            throw  new BusinessException(ErrorResult.likeError());
        }
        //调用API保存数据到Mongodb
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.save(comment);

        //拼接redis的key，将用户的点赞状态存入redis     哪个动态 user 哪个操作
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key,hashKey,"1");
        //返回最新点赞数
        return count;
    }


    //取消点赞
    public Integer dislikeComment(String movementId) {
        //调用API查询用户是否已点赞
        Boolean hasComment = commentApi.hasComment(movementId, UserHolder.getUserId(), CommentType.LIKE);
        //如果未点赞，抛出异常
        if (!hasComment){
            throw  new BusinessException(ErrorResult.disLikeError());
        }
        //调用API，删除数据，返回点赞数量
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.delete(comment);

        //拼接redis的key，删除点赞状态     哪个动态 user 哪个操作
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        //返回最新点赞数
        return count;
    }

    //喜欢
    public Integer loveComment(String movementId) {
        //调用API查询用户是否已喜欢
        Boolean hasComment = commentApi.hasComment(movementId, UserHolder.getUserId(), CommentType.LOVE);
        //如果已经喜欢，抛出异常
        if (hasComment){
            throw  new BusinessException(ErrorResult.loveError());
        }
        //调用API保存数据到Mongodb
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.save(comment);

        //拼接redis的key，将用户的点赞状态存入redis     哪个动态 user 哪个操作
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key,hashKey,"1");
        //返回最新喜欢数
        return count;
    }

    //取消喜欢
    public Integer disloveComment(String movementId) {
        //调用API查询用户是否已点赞
        Boolean hasComment = commentApi.hasComment(movementId, UserHolder.getUserId(), CommentType.LOVE);
        //如果未喜欢，抛出异常
        if (!hasComment){
            throw  new BusinessException(ErrorResult.disloveError());
        }
        //调用API，删除数据，返回点赞数量
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.delete(comment);

        //拼接redis的key，删除喜欢状态     哪个动态 user 哪个操作
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        //返回最新喜欢数
        return count;
    }

    //点赞评论
    public Integer findLikeComment(String id) {
        //判断是否已点赞
        Boolean hasComment = commentApi.findComment(id,UserHolder.getUserId(),CommentType.LIKE);
        if (hasComment){
            throw new BusinessException(ErrorResult.likeError());
        }
        //调用API，添加数据，返回点赞数量
        Comment comment = new Comment();
        comment.setUserId(UserHolder.getUserId());
        comment.setPublishId(new ObjectId(id));
        comment.setCommentType(CommentType.LIKE.getType());
        Integer count = commentApi.saveComment(comment);
        //拼接redis的key，将用户的点赞状态存入redis     哪个动态 user 哪个操作
        String key = Constants.MOVEMENTS_INTERACT_KEY + id;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return count;

    }

    //取消评论
    public Integer  findDisLikeComment(String id) {
        //判断是否已点赞
        Boolean hasComment = commentApi.findComment(id,UserHolder.getUserId(),CommentType.LIKE);
        if (!hasComment){
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //调用API，删除数据，返回点赞数量
        Comment comment = new Comment();
        comment.setUserId(UserHolder.getUserId());
        comment.setPublishId(new ObjectId(id));
        comment.setCommentType(CommentType.LIKE.getType());
        Integer count = commentApi.deleteComment(comment);
        //拼接redis的key，将用户的点赞状态存入redis     哪个动态 user 哪个操作
        String key = Constants.MOVEMENTS_INTERACT_KEY + id;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;

    }
}
